<script setup>
import { buttonClicked } from '@/utils/tool';
import {
  getObtainCouponsList,
  requestCarouselListData,
  hasRentOrder,
  isUnoccupiedPowerBank,
  isFinishDepositWx,
  isFinishPrepay,
  isWechatPowerBank,
  checkPayIsValid,
  isrentboxShow
} from '@/api/my';
import { getUserInfo } from '@/api/profile';

// 定义响应式变量
const carouselList = ref([]);
const isAgree = ref(1);
const qrcode = ref(null);
const deviceId = ref(null);
const wx_score = ref(0);
const onclick = ref(false);
const isIphoneX = ref(false);
const display = ref('visible');
const show = ref(false);
const height = ref(800);
const isContiue = ref(true);
const couponList = ref([]);
const couponText = ref('商家专属优惠卷0.5小时');
const advancedConfig = ref({});
const config = ref({});
const discountTime = ref(0);
const showModal = ref(false);
const { proxy } = getCurrentInstance();

// 页面加载逻辑，获取 deviceId 和 qrcode 参数
onLoad(async (options) => {
  try {
    // const options = uni.getLaunchOptionsSync();
    console.log('Launch options:', options);
    if (!options.q) {
      deviceId.value = uni.getStorageSync('deviceId');
      console.log('Device ID from storage:', deviceId.value);
    } else {
      qrcode.value = decodeURIComponent(options.q); // 解码二维码url
      // 获取deviceId
      deviceId.value = qrcode.value.substring(qrcode.value.indexOf('=') + 1);
      console.log('Decoded device ID:', deviceId.value);
      uni.setStorageSync('deviceId', deviceId.value);
    }

    if (!deviceId.value) {
      console.error('Device ID is not defined');
      return;
    }

    const user = await getUserInfo();
    console.log('User info:', user);
    isIphoneX.value = getApp().globalData.isIphoneX;

    const a = uni.getSystemInfoSync();
    const windowHeight = a.windowHeight * (750 / a.windowWidth);

    uni
      .createSelectorQuery()
      .select('.tou')
      .boundingClientRect((rect) => {
        if (rect) {
          let clientHeight = rect.height;
          let clientWidth = rect.width;
          let ratio = 750 / clientWidth;
          height.value = windowHeight - clientHeight * ratio - 611;
        } else {
          height.value = windowHeight - 100;
        }
      })
      .exec();

    if (deviceId.value) {
      const res = await requestCarouselListData(deviceId.value);
      if (res && res.data.length > 0) {
        carouselList.value = res.data;
        const data = [{ deviceId: deviceId.value }, { advertList: res.data }];
        uni.setStorageSync('advert', data);
      }
    }
    initData(deviceId.value);
  } catch (error) {
    console.error('onLoad error:', error);
  }
});

const showCouponOptions = async () => {
  try {
    const response = await getObtainCouponsList(deviceId.value);
    if (response && response.data.length > 0) {
      couponList.value = response.data;
      uni.showActionSheet({
        itemList: couponList.value.map((coupon) => coupon.name),
        success(res) {
          const selectedCoupon = couponList.value[res.tapIndex];
          uni.navigateTo({
            url: `/pages/coupon/coupon?deviceId=${deviceId.value}&couponId=${selectedCoupon.id}&from=rentRule`
          });
        },
        fail(res) {
          console.log(res.errMsg);
        }
      });
    } else {
      uni.showActionSheet({
        itemList: ['选择优惠券', '取消使用优惠券'],
        success(res) {
          if (res.tapIndex === 0) {
            uni.navigateTo({
              url: '/pages/coupon/coupon?deviceId=' + deviceId.value
            });
          } else if (res.tapIndex === 1) {
            uni.showModal({
              content: '已取消使用优惠券',
              showCancel: false,
              success: function () {
                onSelect({ name: '取消使用优惠券' });
              }
            });
          }
        },
        fail(res) {
          console.log(res.errMsg);
        }
      });
    }
  } catch (error) {
    console.error('Failed to fetch coupons:', error);
  }
};

const aboutUs = () => {
  show.value = true;
};

const onClose = () => {
  show.value = false;
};

const navigateToPage = (page) => {
  uni.navigateTo({ url: page });
};

const pay = async () => {
  try {
    if (onclick.value) return;
    onclick.value = true;
    buttonClicked(); // 正确调用函数，而不是设置属性

    uni.requestSubscribeMessage({
      tmplIds: ['90OsbQX_qF5iKZp5l6-kPD9yClCxHdLAdNGX2o17yvY', 'yGw9cXJdTlWRn8JvWGf7YaRziW-Gz3-Hgif88l_wMP0'],
      complete: async () => {
        await payCommon();
      }
    });
  } catch (error) {
    console.error('pay error:', error);
  }
};

//初始化数据
const initData = async (deviceId) => {
  try {
    buttonClicked(); // 这里不需要传递参数
    if (!deviceId) {
      return;
    }
    const add = uni.getStorageSync('scan');
    const a = add === 0 ? 0 : 1;
    if (add === 0) {
      uni.removeStorageSync('scan');
    }
    const res = await isrentboxShow({ deviceId: parseInt(deviceId, 10), a: a });
    if (res.code !== 200) {
      isAgree.value = 2;
      return;
    }
    if (res.data.type) {
      display1.value = '';
    }
    advancedConfig.value = res.data.advancedConfig;
    config.value = res.data.config;
    wx_score.value = res.data.wx_score;
    discountTime.value = res.data.discountTime / 60;
  } catch (error) {
    console.error('initData error:', error);
  }
};

//微信支付和微信支付分的唤起逻辑
const wechatMiniPay = (data) => {
  try {
    console.log('wechatMiniPay data:', data);
    const { appId, nonceStr, orderUuid, paySign, signType, timeStamp } = data;
    console.log(appId);
    uni.requestPayment({
      timeStamp, //时间戳
      nonceStr, //随机字符
      package: data.package, //固定值
      signType, //签名
      paySign,
      success: (success) => {
        console.log('wechatMiniPay success:', success);
        if (success.errMsg == 'requestPayment:ok') {
          checkPayCirle(orderUuid);
        }
      },
      fail: (res) => {
        console.error('wechatMiniPay fail:' + JSON.stringify(res));
        closeCheckPayCirle();
      },
      complete: () => {
        onclick.value = false;
      }
    });
  } catch (error) {
    console.error('wechatMiniPay error:', error);
  }
};

//微信免押
const wxPayScore = (data) => {
  try {
    console.log('wxPayScore data:', data);
    const { mch_id, nonce_str, sign, sign_type, timestamp, orderUuid } = data;
    wx.openBusinessView({
      businessType: 'wxpayScoreUse',
      extraData: {
        mch_id,
        nonce_str,
        sign,
        package: data.package,
        timestamp,
        sign_type
      },
      success: (res) => {
        console.log('wxPayScore success:', res);
        if (!res.extraData.appid) {
          closeCheckPayCirle();
          return;
        }
        checkPayCirle(orderUuid);
      },
      fail: (res) => {
        console.error('wxPayScore fail:', res);
        closeCheckPayCirle();
      },
      complete: () => {
        onclick.value = false;
      }
    });
  } catch (error) {
    console.error('wxPayScore error:', error);
  }
};

//支付逻辑，确保预支付数据完整
const payCommon = async () => {
  try {
    const rentOrder = await hasRentOrder();
    console.log('rentOrder:', rentOrder);
    if (rentOrder && rentOrder.id) {
      // 确保 rentOrder 和 rentOrder.id 存在
      uni.reLaunch({ url: '/pages/orderdetails/orderdetails?id=' + rentOrder.id });
      uni.showToast({ title: '您已有租借订单', icon: 'none', duration: 2000 });
      return;
    }

    const powerBankStatus = await isUnoccupiedPowerBank(deviceId.value);
    console.log('Power bank status:', powerBankStatus);
    if (!powerBankStatus || powerBankStatus.length === 0) {
      uni.showToast({ title: '当前没有可租借的充电宝', icon: 'none', duration: 2000 });
      return;
    }

    const depositStatus = await isFinishDepositWx();
    console.log('depositStatus:', depositStatus);
    if (depositStatus.data.hadSecurityOrder) {
      uni.reLaunch({ url: '/pages/popup/popup?id=' + deviceId.value });
      return;
    }

    if (wx_score.value == '1') {
      const data = await isWechatPowerBank({ deviceId: deviceId.value });
      console.log('isWechatPowerBank data:', data);
      wxPayScore(data.data);
    } else {
      const data = await isFinishPrepay();
      console.log('isFinishPrepay data:', data.data);
      wechatMiniPay(data.data);
    }
  } catch (error) {
    console.error('payCommon error:', error);
  }
};

const computedStyle = computed(() => ({
  visibility: display.value,
  paddingTop: isIphoneX.value ? '45rpx' : '40rpx'
}));

//检查支付状态的逻辑
const checkPayCirle = (orderUuid) => {
  isContiue.value = true;
  checkPay(orderUuid);
};

const closeCheckPayCirle = () => {
  isContiue.value = false;
};

//处理用户选择
const handleSelectPowerBank = (type) => {
  console.log('Selected power bank type:', type);
  // 处理用户选择的逻辑
  showModal.value = false;
};

const checkPay = (orderUuid) => {
  if (!isContiue.value) return;
  checkPayIsValid(orderUuid)
    .then((res) => {
      console.log('checkPay res:', res);
      if (res.code == 200) {
        uni.reLaunch({ url: '/pages/popup/popup?id=' + deviceId.value });
      } else {
        uni.reLaunch({ url: '/pages/mistake/mistake?message=' + res.msg + '&err=' + deviceId.value });
      }
    })
    .catch((error) => {
      console.error('checkPay error:', error);
    });
};
//获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
</script>

<template>
  <view class="container" :style="{ paddingTop: safeAreaInsets?.top + 'rpx' }">
    <view class="container_bar" :style="{ paddingTop: safeAreaInsets?.top + 'rpx' }"></view>
    <view class="container_title">
      <view class="text_1">大容量充电宝</view>
      <view class="text_1">比你想象的更快一些</view>
    </view>
    <!-- ad-intervals 表示广告组件自动刷新广告内容的时间间隔，以秒为单位 -->
    <!-- #ifdef MP-WEIXIN -->
    <Advertisement></Advertisement>
    <!-- #endif -->
    <view class="images">
      <img src="@/static/images/icon_bg.png" />
    </view>
    <!-- 轮播图 -->
    <view class="carousel">
      <view class="orderid">柜机SN:{{ deviceId }}</view>
    </view>
    <view class="footer">
      <view class="interface">适配接口:</view>
      <view class="footer_img">
        <view class="images_1">ios</view>
        <view class="images_2">Type C</view>
        <view class="images_3">Android</view>
      </view>
      <view class="charging">
        <view class="footer_text">计费规则:</view>
        <view class="footer_minute">3元/60分钟，每天封顶30元，总封顶99元。前三分钟内归还免费</view>
      </view>
      <view class="copon" :class="['copon', { 'iphone-x': isIphoneX }]" :style="computedStyle">
        <image src="@/static/images/icon_copo.png" class="copon_img"></image>
        <text class="copon_text" @tap="showCouponOptions">{{ couponText }}</text>
      </view>
      <button class="depositPayment" plain="true" @click="showModal = true">
        <view class="rent">免押金租借</view>
      </button>
      <powerBank-modal :show="showModal" @select="handleSelectPowerBank" @close="showModal = false"></powerBank-modal>
      <view class="weixin">
        <image src="@/static/images/icon_wxscore.png" style="width: 34rpx; height: 34rpx; margin-right: 10rpx" />
        微信支付分|550分及以上优享
      </view>
      <view class="entrust">
        <text class="agree">点击使用视为同意</text>
        <text class="authorization" @click="navigateToPage('/pages/privacy/privacy')">《用户协议》</text>
        <text class="authorization" @click="navigateToPage('/pages/agreement/agreement')">《委托扣款授权书》</text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
$primary-color: #ff6700;
$secondary-color: #889dba;
$background-color: #e8f1f8;
$font-color: #333;
$light-color: #ececec;

@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

@mixin text-style($size, $weight: normal, $color: $font-color) {
  font-size: $size;
  font-weight: $weight;
  color: $color;
}

// 页面样式
page {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.container {
  background: linear-gradient(to bottom, $background-color 0%, $secondary-color 100%);
  .container_title {
    padding-top: 80rpx;
    text-align: center;
    font-weight: bold;

    .text_1 {
      @include text-style(50rpx, bold);
    }
  }

  .carousel {
    position: relative;
    width: 100%;
    height: 100%;
    z-index: 1;
    .orderid {
      position: absolute;
      top: 106rpx;
      right: 0rpx;
      padding: 10rpx 0rpx 10rpx 10rpx;
      border-radius: 30rpx 0rpx 0rpx 30rpx;
      width: 300rpx;
      text-align: center;
      background-color: rgb(0, 0, 0);
      color: rgb(255, 255, 255);
      opacity: 0.5;
      z-index: 9999;
    }
  }
  .images {
    @include flex-center;
    margin-top: 40rpx;
    height: 27vh;
  }
  .footer {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin-top: 168rpx;
    height: 40vh;
    background-color: #ffffff;
    border-radius: 32rpx 32rpx 0 0;

    .interface {
      padding: 40rpx 0 20rpx 40rpx;
      font-weight: bold;
    }
    .footer_img {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      margin: 0 50rpx;
      height: 60rpx;
      line-height: 60rpx;
      text-indent: 75rpx;
      font-size: 26rpx;
      background-color: #f4f7fa;

      .images_1,
      .images_2,
      .images_3 {
        background-repeat: no-repeat;
        background-position: left center;
        background-size: 66rpx;
      }
      .images_1 {
        background-image: url('@/static/images/icon_ios.png');
      }
      .images_2 {
        background-image: url('@/static/images/icon_type_c.png');
      }
      .images_3 {
        background-image: url('@/static/images/icon_android.png');
      }
    }
    .charging {
      display: flex;
      flex-direction: row;
      align-items: stretch;
      margin: 40rpx 0 0 50rpx;

      .footer_text {
        width: 130rpx;
        font-size: 28rpx;
        font-weight: bold;
      }
      .footer_minute {
        width: 500rpx;
        font-size: 28rpx;
        font-weight: 400;
        word-wrap: break-word;
      }
    }
    .copon {
      display: flex;
      align-items: center;
      justify-content: center;
      .copon_img {
        width: 42rpx;
        height: 42rpx;
      }
      .copon_text {
        margin-left: 18rpx;
        font-size: 30rpx;
        color: #c4864a;
      }
    }
    .depositPayment {
      margin-top: 5rpx;
      width: 540rpx;
      height: 120rpx;
      border: none;
      border-radius: 16rpx;
      background: url('@/static/images/icon_button.png') no-repeat center center;
      background-size: cover;

      .rent {
        color: #ffffff;
        font-size: 32rpx;
        line-height: 100rpx;
      }
    }
    .weixin {
      @include flex-center;
      font-size: 25rpx;
      color: rgba(157, 157, 157, 1);

      .copon_img {
        width: 34rpx;
        height: 34rpx;
        margin-right: 10rpx;
      }
    }
    .entrust {
      @include flex-center;
      font-size: 25rpx;
      color: rgba(7, 193, 96, 1);
      margin-bottom: 20rpx;

      .agree {
        color: rgba(157, 157, 157, 1);
      }
    }
  }
}
</style>
